package com.ximi.ximimall.authcenter.service;

import cn.hutool.core.util.StrUtil;
import com.ximi.ximimall.authcenter.domain.LitemallUserDetails;
import com.ximi.ximimall.model.LitemallUser;
import com.ximi.ximimall.model.LitemallUserExample;
import com.ximi.ximimall.mapper.LitemallUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author 西米的风
 * @description TODO
 * @date 2022-10-13 23:23
 */
@Slf4j
@Component
public class XimiUserDetailService  implements UserDetailsService {
    @Autowired
    private LitemallUserMapper litemallUserMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        if(StrUtil.isNotBlank(userName)) {
            LitemallUser litemallUser = getByUsername(userName);
            if(null != litemallUser) {
                log.info("根据用户名:{}获取用户登陆信息:{}",userName,litemallUser);
                LitemallUserDetails litemallUserDetails = new LitemallUserDetails(litemallUser);
                return litemallUserDetails;
            }
            log.warn("根据用户名没有查询到对应的用户信息:{}",userName);
        }
        log.warn("当前用户名为:{}",userName);
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    private LitemallUser getByUsername(String userName) {
        LitemallUserExample litemallUserExample = new LitemallUserExample();
        litemallUserExample.createCriteria().andUsernameEqualTo(userName);
        List<LitemallUser> userList = litemallUserMapper.selectByExample(litemallUserExample);
        if (!CollectionUtils.isEmpty(userList)) {
            return userList.get(0);
        }
        return null;
    }
}
